import 'package:BeeApp/MainPage/MainOrderEndNewsPage.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:BeeApp/ShopPage/UserOrderNewsPage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MainXTNewsPage extends StatefulWidget {
  final String orderID;
  MainXTNewsPage(this.orderID, {Key key}) : super(key: key);

  @override
  _MainXTNewsPageState createState() => _MainXTNewsPageState();
}

class _MainXTNewsPageState extends State<MainXTNewsPage> {
  List<CellModel> cellArr = [];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int page = 1;

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    page = 1;
    cellArr?.clear();
    getCellNews();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    // items.add((items.length + 1).toString());
    page = page + 1;
    getCellNews();
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    _onRefresh();
    removeNew();
  }

  void removeNew() {
    DioUtils.postHttp(
      context,
      "Usercenter/news_update",
      parameters: {
        "token": getData("token"),
        "order_id": widget.orderID,
      },
      onSuccess: (t) {
        print(t);
      },
      onError: (error) {
        print(error);
      },
    );
  }

  void getCellNews() {
    DioUtils.postHttp(
      context,
      "Usercenter/news_list",
      parameters: {
        "token": getData("token"),
        "order_id": widget.orderID,
        "page": page.toString(),
      },
      onSuccess: (t) {
        print(t);
        ListModel model = ListModel.fromJson(t);
        if (model.code == 1) {
          if (mounted) {
            setState(() {
              List<CellModel> arr = model.data;
              for (var i = 0; i < arr.length; i++) {
                cellArr.add(arr[i]);
              }
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: getAppBar(context, "系统消息"),
        body: SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: WaterDropHeader(),
          footer: CustomFooter(
            builder: (BuildContext context, LoadStatus mode) {
              Widget body;
              if (mode == LoadStatus.idle) {
                body = Text("上拉加载");
              } else if (mode == LoadStatus.loading) {
                body = CupertinoActivityIndicator();
              } else if (mode == LoadStatus.failed) {
                body = Text("加载失败！点击重试！");
              } else if (mode == LoadStatus.canLoading) {
                body = Text("松手,加载更多!");
              } else {
                body = Text("没有更多数据了!");
              }
              return Container(
                height: 55.0,
                child: Center(child: body),
              );
            },
          ),
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: cellArr == null || cellArr.length == 0
              ? Container()
              : ListView.builder(
                  itemCount: cellArr.length,
                  itemBuilder: (BuildContext context, int index) {
                    return InkWell(
                      child: Container(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              padding: EdgeInsets.only(
                                  left: setWidth(30),
                                  right: setWidth(30),
                                  top: setWidth(20)),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    cellArr[index].content,
                                    style: TextStyle(
                                      color: Color(0xFF333333),
                                      fontSize: setFontSize(32),
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: <Widget>[
                                      Text(
                                        cellArr[index].createtimeText,
                                        style: TextStyle(
                                          color: Color(0xFF999999),
                                          fontSize: setFontSize(30),
                                        ),
                                      )
                                    ],
                                  ),
                                  SizedBox(height: 8),
                                ],
                              ),
                            ),
                            Container(
                              width: 900,
                              height: 1,
                              color: Colors.grey,
                            ),
                          ],
                        ),
                      ),
                      onTap: () {
                        print("object" + index.toString());
                        String orderID = cellArr[index].orderId.toString();
                        if (cellArr[index].orderStatus == null) {
                          showToast("订单为空");
                          return;
                        }
                        if (cellArr[index].orderStatus < 5) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) =>
                                    UserOrderNewsPage(orderID)),
                          );
                        } else {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) =>
                                    MainOrderEndNewsPage(orderID, true)),
                          );
                        }

                        // Navigator.push(context,
                        //     MaterialPageRoute(builder: (context) => PingTaiGGNewsPage()));
                      },
                    );
                  },
                ),
        ));
  }
}

class ListModel {
  int code;
  String msg;
  String time;
  List<CellModel> data;

  ListModel({this.code, this.msg, this.time, this.data});

  ListModel.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    msg = json['msg'];
    time = json['time'];
    if (json['data'] != null) {
      data = new List<CellModel>();
      json['data'].forEach((v) {
        data.add(new CellModel.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['code'] = this.code;
    data['msg'] = this.msg;
    data['time'] = this.time;
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CellModel {
  int id;
  int orderId;
  int userId;
  String content;
  int num;
  int createtime;
  String createtimeText;
  int orderStatus;

  CellModel(
      {this.id,
      this.orderId,
      this.userId,
      this.content,
      this.num,
      this.createtime,
      this.createtimeText,
      this.orderStatus});

  CellModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    orderId = json['order_id'];
    userId = json['user_id'];
    content = json['content'];
    num = json['num'];
    createtime = json['createtime'];
    createtimeText = json['createtime_text'];
    orderStatus = json['order_status'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['order_id'] = this.orderId;
    data['user_id'] = this.userId;
    data['content'] = this.content;
    data['num'] = this.num;
    data['createtime'] = this.createtime;
    data['createtime_text'] = this.createtimeText;
    data['order_status'] = this.orderStatus;
    return data;
  }
}
